from django.conf import settings
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from itsdangerous import BadData

def generate_save_user_token(openid):
    '''使用Itsdangrous保存openID，生成access_token'''
    #serializer=Serializer(密钥，有效期秒）
    serializer=Serializer(settings.SECRET_KEY,300)
    #serializer.dumps(数据），返回bytes类型
    data ={'openid':openid}
    token=serializer.dumps(data)
    return token

def check_save_user_token(access_token):
    '''使用Itsdangrous提取access_token中的openID'''
    #serializer=Serializer(密钥，有效期秒)
    serializer=Serializer(settings.SECRET_KEY,300)
    try:
        data=serializer.loads(access_token)

    except BadData:
        #验证失败，会抛出itsdangerous.BadData异常
        return None
    else:
        #校验成功，返回access_token中的openID
        return data['openid']


